#!/usr/bin/env python

# (c) 2007-2011 Helsinki University of Technology and University of Helsinki
# Licensed under the MIT license; see LICENSE.txt for more information.

from harava.map import Mapper
from harava.rdf import *

LOOKUP2FIELD = (
  ('tosu.activity', TOSU.activity),
  ('tosu.worktime', TOSU.workTime),
  ('tosu.keyfactor', TOSU.keyFactor),
  ('tosu.theme', DCTERMS.subject),
  ('ts.tero', DCTERMS.subject),
)


class ToSuVoluntaryMapper (Mapper):
  def __init__(self, session):
    Mapper.__init__(self, session)
    
  def literal2keyword(self, literal):
    """Convert a RDF Literal into a unicode keyword; if it contains dash hierarchy notation, return only the last part."""
    kw = unicode(literal)
    kw = kw.split(' - ')[-1]
    kw = kw.split(u' \u2013 ')[-1] # EN DASH
    kw = kw.split(u' \u2014 ')[-1] # EM DASH
    return kw

  def process(self, doc):
    lookup = self._session.getLookupService()

    for literal in list(doc.getMetadata(TOSU.actionType)):
      if not isinstance(literal, Literal): continue
      
      kw = self.literal2keyword(literal)

      for scheme, prop in LOOKUP2FIELD:
        uris = lookup.lookup(doc, scheme, kw, language=literal.language, warn=False)
        if uris:
          doc.log('NOTE', 'map', 'Keyword lookup successful using scheme %s' % scheme, literal)
          doc.clearMetadata(TOSU.actionType, literal)
          for uri in uris:
            doc.setMetadata(prop, uri)
          break
          
    # target group lookup
    for literal in list(doc.getMetadata(TOSU.targetGroup)):
      if not isinstance(literal, Literal): continue
      
      kw = self.literal2keyword(literal)

      uris = lookup.lookup(doc, 'tosu.targetgroup', kw, language=literal.language, warn=False)
      if uris:
        doc.log('NOTE', 'map', 'Target group lookup successful using scheme %s' % scheme, literal)
        doc.clearMetadata(TOSU.targetGroup, literal)
        for uri in uris:
          doc.setMetadata(TOSU.target, uri)
        break
    
    # kunnat lookup
    for kw in doc.getMetadata(DCTERMS.spatial):
      if not isinstance(kw, Literal): continue

      uris = lookup.lookup(doc, 'kunnat', unicode(kw), language=kw.language, warn=True)
      if uris:
        doc.log('NOTE', 'map', 'Municipality lookup successful using scheme kunnat', kw)
        doc.clearMetadata(DCTERMS.spatial, kw)
        for uri in uris:
          doc.setMetadata(DCTERMS.spatial, uri)
    
    # language lookup
    for kw in doc.getMetadata(DCTERMS.language):
      if not isinstance(kw, Literal): continue
      
      uris = lookup.lookup(doc, 'language', unicode(kw), language=kw.language, warn=True)
      if uris:
        doc.log('NOTE', 'map', 'Language lookup successful using scheme language', kw)
        doc.clearMetadata(DCTERMS.language, kw)
        for uri in uris:
          doc.setMetadata(DCTERMS.language, uri)
    

    doc.setCompleted('map')
    self._session.schedule(doc)
    return True

  def finish(self):
    pass
